package com.qfedu.controller;

import com.qfedu.entity.User;
import com.qfedu.service.intf.UserService;
import com.qfedu.utils.VerifyCodeUtil;
import com.qfedu.vo.PageVo;
import com.qfedu.vo.R;
import org.apache.ibatis.annotations.Delete;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/api/user/")
public class UserController {
    @Resource
    UserService service;

    @PostMapping("add.do")
    public R add(@DateTimeFormat User user) {
        System.out.println("aaaaaa");
        return service.add(user);
    }

    @PostMapping("del.do")
    public R del(int id) {
        return service.del(id);
    }

    @PostMapping("update.do")
    public R update(User user) {
        return service.update(user);
    }


    @GetMapping("all.do")
    public PageVo all(int page, int limit, String username) {
        System.out.println(username);
        PageVo pageVo = service.queryPage(page, limit, username);
        System.out.println(pageVo);
        return pageVo;
    }

    @GetMapping("selectAll.do")
    public R selectAll() {
        return service.selectAll();
    }

    @GetMapping("is.do")
    public R is(User user, HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute("code");
        String a = "";
        for (int i = 0; i < code.length(); i++) {
            a += code.charAt(i);
        }
        System.out.println(user.getYzm());
        System.out.println(code);
        System.out.println(user.getYzm().equalsIgnoreCase(a));
        return service.login(user, a);
    }

    @GetMapping("createcode.do")
    public void createImg(HttpServletResponse response, HttpSession session) throws IOException {
        //1.生成对应宽高的初始图片
        BufferedImage verifyImg = new BufferedImage(200, 50, BufferedImage.TYPE_INT_RGB);
        //2.单独的一个类方法，出于代码复用考虑，进行了封装。功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
        String randomText = VerifyCodeUtil.drawRandomText(200, 50, verifyImg);
        //3.服务端记录验证码
        session.setAttribute("code", randomText);
        //4.必须设置响应内容类型为图片，否则前台不识别
        response.setContentType("image/png");
        //5.写出图片
        ImageIO.write(verifyImg, "png", response.getOutputStream());
    }
}
